package models;

import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import com.avaje.ebean.annotation.CreatedTimestamp;
import com.avaje.ebean.annotation.UpdatedTimestamp;

import play.db.ebean.Model;
import util.MyUtil;

@Entity
public class User extends Model {
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Long id;

	public String fullName;
	
	@Column(unique = true, nullable = true)
	public Long fbId;

	@Column(unique = true, nullable = true)
	public Long filyouId; 
	
	@Column(nullable = false)
	public boolean filyouLinked = false; 
	
	@Column(unique = true, nullable = true)
	public Long calendaryouId;
	
	@Column(nullable = false)
	public boolean calendaryouLinked = false;
	
	@Column(nullable = true, unique = true)
	public Long emaiyouId;
	
	@Column(nullable = false)
	public boolean emaiyouLinked = false;
	
	@Column(nullable = true, unique = true)
	public Long peopleyouId;
	
	@Column(nullable = false)
	public boolean peopleyouLinked = false;

	@Column(nullable = false, length = 30, unique = true)
	public String username;
	
	public String email;
	
	public String pictureUrl;
	
	@Column(nullable = false)
	private String password;
	
	@CreatedTimestamp
	private Date createdAt;

	@UpdatedTimestamp
	private Date updatedAt;
	
	public static final Finder<Long,User> finder = new Model.Finder<Long, User>(Long.class, User.class); 

	public boolean validatePassword(String password) {
		String encPass = encryptMd5(password);
		return this.password.equals(encPass);
	}
	
	private static String encryptMd5(String string) {
		try {
			return MyUtil.stringToMD5(string);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
	}
			
	public void setPassword(String password) {
		this.password = encryptMd5(password);
	}
		
	public Date getCreatedAt() {
		return createdAt;
	}

	public Date getUpdatedAt() {
		return updatedAt;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", fullName=" + fullName + ", filyouId="
				+ filyouId + ", filyouLinked=" + filyouLinked
				+ ", calendaryouId=" + calendaryouId + ", calendaryouLinked="
				+ calendaryouLinked + ", username=" + username + ", email="
				+ email + ", pictureUrl=" + pictureUrl + ", password="
				+ password + ", createdAt=" + createdAt + ", updatedAt="
				+ updatedAt + "]";
	}
}
